package com.wpw.java8demo;

import org.junit.Test;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @Description
 * @ClassName CompletableFutureTest
 * @Author wupengwei
 * @Date 2022/3/31 10:40
 */
public class CompletableFutureTest {

    @Test
    public void completableFutureTest1() throws ExecutionException, InterruptedException {
        Future<Double> ddfe = getPriceAsync("product");
        System.out.println("do others");
        Double aDouble = ddfe.get();
        System.out.println(aDouble);
    }

    public Future<Double> getPriceAsync(String product) {
        CompletableFuture<Double> futurePrice = new CompletableFuture<>();
        new Thread( () -> {
            double price = calculatePrice(product);
            futurePrice.complete(price);
        }).start();
        return futurePrice;
    }

    private double calculatePrice(String product) {
        delay();
        System.out.println("calculatePrice");
        Random random = new Random();
        return random.nextDouble() * product.charAt(0) + product.charAt(1);
    }
    public static void delay() {
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
